const RoleModel = require('../models/roleModel');
const DataPermissionModel = require('../models/dataPermissionModel');
const PermissionModel = require('../models/permissionModel');
const { getLogger } = require('../logger');
const logger = getLogger('controllers.roleController');
const { success, error, serverError, notFound, badRequest } = require('../utils/response');
const { logAudit } = require('../utils/auditLogger');
const { validateRequired, validateId, validateArray } = require('../utils/validator');
const { generateCacheKey, getCacheKeyPattern } = require('../cache/utils/cacheKeyGenerator');

const cacheService = require('../cache/cacheService');

// 在需要新功能时使用cacheService，保持向后兼容
const { isSuperAdminById } = require('../utils/utils');

// 获取所有角色
const getAllRoles = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        
        // 构建过滤条件
        const filters = {};
        if (req.query.name) filters.name = req.query.name;
        if (req.query.code) filters.code = req.query.code;
        if (req.query.status !== undefined) filters.status = parseInt(req.query.status);
        if (req.query.is_protected !== undefined) filters.is_protected = parseInt(req.query.is_protected);

        // 搜索值
        if (req.query.searchvalue) {
            filters.searchvalue = req.query.searchvalue;
        }

        // 从认证中间件获取当前用户ID
        const currentUserId = req.user?.id;
        
        // 生成缓存键
        const cacheKey = generateCacheKey('role', 'list', `page_${page}_limit_${limit}_user_${currentUserId || 'anonymous'}`);
        
        // 尝试从缓存获取数据
        const cachedData = await cacheService.get(cacheKey);
        if (cachedData) {
            logger.info('从缓存获取角色列表数据', { page, limit, filters });
            await logAudit(req, { action_type: 'view', module_code: 'role', business_type: 'list', operation_desc: 'list' });
            return success(req, res, '获取角色列表成功', cachedData);
        }
        
        let maxPermissionLevel = null;
        
        // 如果不是超级管理员，需要获取当前用户的最大权限层级
        if (currentUserId && !(await isSuperAdminById(currentUserId))) {
            const query = `
                SELECT MAX(r.permission_level) as max_level 
                FROM user_role ur
                JOIN role r ON ur.role_id = r.id
                WHERE ur.user_id = ?
            `;
            // 使用Model方法替代直接db调用
            maxPermissionLevel = await RoleModel.getUserMaxPermissionLevel(currentUserId);
        }
        
        const [roles, total] = await Promise.all([
            RoleModel.getAllRoles(page, limit, filters, currentUserId, maxPermissionLevel),
            RoleModel.getRoleCount(filters, currentUserId, maxPermissionLevel)
        ]);

        const responseData = {
            data: roles,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        };
        
        // 将结果存入缓存
        await cacheService.set(cacheKey, responseData);
        logger.info('将角色列表数据存入缓存', { page, limit, filters });

        await logAudit(req, { action_type: 'view', module_code: 'role', business_type: 'list', operation_desc: 'list' });
        success(req, res, '获取角色列表成功', responseData);
    } catch (err) {
        logger.error('获取角色列表错误', { error: err });
        serverError(req, res, '获取角色列表失败');
    }
};

// 获取角色详情
const getRoleById = async (req, res) => {
    const { id } = req.params;
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        const currentUserId = req.user?.id;
        
        // 生成缓存键，符合命名规范
        const cacheKey = generateCacheKey('role', 'item', `role_${id}_user_${currentUserId || 'anonymous'}`);
        
        // 尝试从缓存获取数据
        const cachedData = await cacheService.get(cacheKey);
        if (cachedData) {
            logger.info('从缓存获取角色详情数据', { roleId: id });
            await logAudit(req, { action_type: 'view', module_code: 'role', business_type: 'detail', operation_desc: 'detail', target_entity_type: 'role', target_entity_id: id });
            return success(req, res, '获取角色信息成功', cachedData);
        }

        const role = await RoleModel.findById(id, currentUserId);
        if (!role) {
            return notFound(req, res, '角色不存在');
        }
        
        // 将结果存入缓存，使用策略参数
        await cacheService.set(cacheKey, role, null, 'userPermissions');
        logger.info('将角色详情数据存入缓存', { roleId: id });

        await logAudit(req, { action_type: 'view', module_code: 'role', business_type: 'detail', operation_desc: 'detail', target_entity_type: 'role', target_entity_id: id });
        success(req, res, '获取角色信息成功', role);
    } catch (err) {
        logger.error('获取角色信息错误', { error: err });
        serverError(req, res, '获取角色信息失败');
    }
};

// 创建角色
const createRole = async (req, res) => {
    try {
        const { formdata = {}, menus = [], permissions = [] } = req.body || {};
        const { name, code, description, permission_level, role_type, data_scope, dept_id, remark, effective_time, expire_time, data_scope_dept_ids } = formdata;
        const requiredValidation = validateRequired(formdata, ['name','role_type','dept_id']);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }
        if (code) {
            const codeExists = await RoleModel.isCodeExists(code);
            if (codeExists) {
                return badRequest(req, res, '角色编码已存在');
            }
        }
        const nameExists = await RoleModel.isNameExists(name);
        if (nameExists) {
            return badRequest(req, res, '角色名称已存在');
        }
        const currentUserId = req.user?.id;
        let scopeDeptIds = data_scope_dept_ids;
        if (Array.isArray(scopeDeptIds)) {
            scopeDeptIds = scopeDeptIds.join(',');
        }

        const params = {
            name,
            code,
            description,
            role_type,
            data_scope,
            data_scope_dept_ids: scopeDeptIds || null,
            dept_id,
            remark,
            permission_level,
            effective_time,
            expire_time,
            create_by: currentUserId
        };
        // 创建角色
        const roleId = await RoleModel.create(params,currentUserId);
        if (Array.isArray(menus) && menus.length > 0) {
            // 绑定菜单
            await RoleModel.bindMenus(roleId, menus, currentUserId);
        }
        if (Array.isArray(permissions) && permissions.length > 0) {
            // 绑定权限
            await PermissionModel.assignPermissionsToRole(roleId, permissions, currentUserId);
        }
        await logAudit(req, { action_type: 'create', module_code: 'role', business_type: 'role', operation_desc: 'create', target_entity_type: 'role', target_entity_id: roleId, target_entity_name: name, after_data: { ...params, menus, permissions } });
        success(req, res, '角色创建成功', { id: roleId, ...params, menus, permissions });
    } catch (err) {
        logger.error('创建角色错误', { error: err });
        serverError(req, res, '创建角色失败');
    }
};

// 更新角色
const updateRole = async (req, res) => {
    try {
        const { formdata = {}, menus = [], permissions = [] } = req.body || {};
        const id = formdata.id || req.body.id;
        if (!validateId(id)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        const currentUserId = req.user?.id;
        const existingRole = await RoleModel.findById(id, currentUserId);
        if (!existingRole) {
            return notFound(req, res, '角色不存在');
        }
        const permission_level = formdata.permission_level;
        if (!(await isSuperAdminById(currentUserId))) {
            // 使用Model方法替代直接db调用
            const userMaxLevel = await RoleModel.getUserMaxPermissionLevel(currentUserId);
            const role = await RoleModel.getRolePermissionInfo(id);
            if (!role) {
                return error(res, '角色不存在', 404);
            }
            if (userMaxLevel < role.permission_level || (permission_level && permission_level > userMaxLevel)) {
                return error(req, res, '无权修改该角色');
            }
        }
        
        const name = formdata.name;
        const code = formdata.code;
        if (code && code !== existingRole.code) {
            const codeExists = await RoleModel.isCodeExists(code, id);
            if (codeExists) {
                return badRequest(req, res, '角色编码已存在');
            }
        }
        if (name && name !== existingRole.name) {
            const nameExists = await RoleModel.isNameExists(name, id);
            if (nameExists) {
                return badRequest(req, res, '角色名称已存在');
            }
        }
        let scopeDeptIds = formdata.data_scope_dept_ids;
        if (Array.isArray(scopeDeptIds)) {
            scopeDeptIds = scopeDeptIds.join(',');
        }
        const updateData = {
            name: name !== undefined ? name : existingRole.name,
            code: code !== undefined ? code : existingRole.code,
            description: formdata.description !== undefined ? formdata.description : existingRole.description,
            status: formdata.status !== undefined ? parseInt(formdata.status) : existingRole.status,
            role_type: formdata.role_type !== undefined ? formdata.role_type : existingRole.role_type,
            data_scope: formdata.data_scope !== undefined ? formdata.data_scope : existingRole.data_scope,
            data_scope_dept_ids: scopeDeptIds !== undefined ? scopeDeptIds : existingRole.data_scope_dept_ids || null,
            dept_id: formdata.dept_id !== undefined ? formdata.dept_id : existingRole.dept_id,
            remark: formdata.remark !== undefined ? formdata.remark : existingRole.remark,
            effective_time: formdata.effective_time !== undefined ? formdata.effective_time : existingRole.effective_time,
            expire_time: formdata.expire_time !== undefined ? formdata.expire_time : existingRole.expire_time,
            permission_level: formdata.permission_level !== undefined ? formdata.permission_level : existingRole.permission_level,
            create_by: existingRole.create_by // 保持原有的create_by值
        };
        if (permission_level !== undefined && !existingRole.is_system) {
            updateData.permission_level = permission_level;
        }


        const affectedRows = await RoleModel.update(id, updateData, currentUserId);
        if (affectedRows > 0) {
            // 处理菜单绑定 - 如果menus为数组（包括空数组），都需要更新绑定
            if (Array.isArray(menus)) {
                if (menus.length === 0) {
                    // 如果menus为空数组，清空所有菜单绑定
                    await RoleModel.unbindAllMenus(id, currentUserId);
                } else {
                    // 如果menus有内容，重新绑定菜单
                    await RoleModel.bindMenus(id, menus, currentUserId);
                }
            }
            
            // 处理权限绑定 - 如果permissions为数组（包括空数组），都需要更新绑定
            if (Array.isArray(permissions)) {
                if (permissions.length === 0) {
                    // 如果permissions为空数组，清空所有权限绑定
                    await PermissionModel.removeAllPermissionsFromRole(id, currentUserId);
                } else {
                    // 如果permissions有内容，重新绑定权限
                    await PermissionModel.assignPermissionsToRole(id, permissions, currentUserId);
                }
            }
            
            // 清除相关用户的权限缓存
            
            
            // 使用新的缓存服务清除角色详情缓存
            await cacheService.del(generateCacheKey('role','item', id));
            logger.info('清除角色详情缓存', { roleId: id });
            
            // 清除角色列表缓存
            await cacheService.clearByPattern(getCacheKeyPattern('role','list'));
            logger.info('清除角色列表缓存');
            
            const updatedRole = await RoleModel.findById(id, currentUserId);
            await logAudit(req, { action_type: 'update', module_code: 'role', business_type: 'role', operation_desc: 'update', target_entity_type: 'role', target_entity_id: id, target_entity_name: updatedRole.name, before_data: existingRole, after_data: { ...updatedRole, menus, permissions } });
            success(req, res, '角色更新成功', { ...updatedRole, menus, permissions });
        } else {
            serverError(req, res, '角色更新失败');
        }
    } catch (err) {
        logger.error('更新角色错误', { error: err });
        serverError(req, res, '更新角色失败');
    }
};

// 删除角色
const removeRole = async (req, res) => {
    const { id } = req.params;
    
    try {
        
        if (!validateId(id)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        // 检查角色是否存在
        const currentUserId = req.user?.id;
        const existingRole = await RoleModel.findById(id, currentUserId);
        if (!existingRole) {
            return notFound(req, res, '角色不存在');
        }

        // 检查角色是否可以删除
        const deletable = await RoleModel.isDeletable(id);
        if (!deletable) {
            return badRequest(req, res, '该角色为保护角色或已绑定用户/菜单，无法删除');
        }
        
        // 获取绑定该角色的所有用户ID
        const roleUsers = await RoleModel.getRoleUsers(id);

        // 删除角色
        const affectedRows = await RoleModel.deleteById(id);
        
        if (affectedRows > 0) {
            // 手动删除角色相关的菜单和权限绑定（因为使用的是软删除，不会触发ON DELETE CASCADE）
            await RoleModel.unbindAllMenus(id, currentUserId);
            await PermissionModel.removeAllPermissionsFromRole(id);
            
            // 清除相关用户的权限缓存
            // await PermissionModel.clearPermissionCache();
            
            await logAudit(req, { action_type: 'delete', module_code: 'role', business_type: 'role', operation_desc: 'delete', target_entity_type: 'role', target_entity_id: id, target_entity_name: existingRole.name, before_data: existingRole });
            success(req, res, '角色删除成功');
        } else {
            serverError(req, res, '角色删除失败');
        }
    } catch (err) {
        logger.error('删除角色错误', { error: err });
        serverError(req, res, '角色删除失败');
    }
};

// 获取用户已绑定的角色
const getBindRoles = async (req, res) => {
    const page = parseInt(req.body.page) || 1;
    const limit = parseInt(req.body.limit) || 10;
    
    // 构建过滤条件
    const filters = {};
    if (req.body.name) filters.name = req.body.name;
    if (req.body.code) filters.code = req.body.code;
    if (req.body.userid) filters.userid = req.body.userid;
    if (req.body.status !== undefined) filters.status = parseInt(req.body.status);
    if (req.body.is_protected !== undefined) filters.is_protected = parseInt(req.body.is_protected);
    
    try {
        if (!validateId(req.body.userid)) {
            return badRequest(req, res, '用户ID格式错误');
        }
        
        const [roles, total] = await Promise.all([
            RoleModel.getBindRoles(page, limit, filters),
            RoleModel.getBindRoleCount(filters)
        ]);

        success(req, res, '获取用户绑定角色成功', {
            data:roles,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        });

        // const roles = await RoleModel.getBindRoles(page, limit, filters);
        // success(req, res, '获取用户绑定角色成功', roles);
    } catch (err) {
        logger.error('获取用户绑定角色错误', { error: err });
        serverError(req, res, '获取用户绑定角色失败');
    }
};


// 角色绑定用户
const batchBindUsers = async (req, res) => {
    const { roleId, userIds } = req.body;
    
    try {
        // 输入验证
        const requiredValidation = validateRequired(req.body, ['roleId', 'userIds']);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }

        if (!validateId(roleId)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        const userIdsValidation = validateArray(userIds, '用户ID');
        if (!userIdsValidation.isValid) {
            return badRequest(req, res, userIdsValidation.message);
        }

        // 验证所有用户ID格式
        for (const userId of userIds) {
            if (!validateId(userId)) {
                return badRequest(req, res, '用户ID格式错误');
            }
        }

        
        const currentUserId = req.user?.id;
        
        const result = await RoleModel.bindUsers(roleId, userIds, currentUserId);   
        
        
        success(req, res, '角色绑定用户成功', { affectedRows: result });
    } catch (err) {
        logger.error('角色绑定用户错误', { error: err });
        serverError(req, res, '绑定角色用户失败');
    }
};

// 角色绑定菜单
const bindMenus = async (req, res) => {
    const { roleId, menuIds } = req.body;
    
    try {
        // 输入验证
        const requiredValidation = validateRequired(req.body, ['roleId', 'menuIds']);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }

        if (!validateId(roleId)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        const menuIdsValidation = validateArray(menuIds, '菜单ID');
        if (!menuIdsValidation.isValid) {
            return badRequest(req, res, menuIdsValidation.message);
        }

        // 验证所有菜单ID格式
        for (const menuId of menuIds) {
            if (!validateId(menuId)) {
                return badRequest(req, res, '菜单ID格式错误');
            }
        }

        // 从认证中间件获取当前用户ID
        const currentUserId = req.user?.id;

        const result = await RoleModel.bindMenus(roleId, menuIds, currentUserId);
        
        // 获取绑定该角色的所有用户ID
        const roleUsers = await RoleModel.getRoleUsers(roleId);
        for (const user of roleUsers) {
            await cacheService.del(generateCacheKey('user','roles', user.user_id));
            logger.info('角色菜单绑定变更，已清除用户缓存', { userId: user.user_id, roleId });
        }
        
        success(req, res, '角色菜单绑定成功', { affectedRows: result });
    } catch (err) {
        logger.error('绑定角色菜单错误', { error: err });
        serverError(req, res, '绑定角色菜单失败');
    }
};

// 获取角色已绑定的菜单
const getBindMenus = async (req, res) => {
    const { id } = req.params;
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '角色ID格式错误');
        }
        // 获取当前用户ID
        const currentUserId = req.user?.id;
        const isSuperAdmin = await isSuperAdminById(id);
        
        // 生成缓存键，符合命名规范
        const cacheKey = generateCacheKey('menu', 'list', `role_${id}`);
        
        // 尝试从缓存获取数据
        const cachedMenus = await cacheService.get(cacheKey);
        if (cachedMenus) {
            logger.info('从缓存获取角色绑定菜单', { roleId: id, isSuperAdmin });
            return success(req, res, '获取角色绑定菜单成功', cachedMenus);
        }
        
        const menus = await RoleModel.getBindMenus(id, currentUserId, isSuperAdmin);
        
        // 将结果存入缓存，使用策略参数
        await cacheService.set(cacheKey, menus, null, 'userPermissions');
        logger.info('将角色绑定菜单存入缓存', { roleId: id, isSuperAdmin });
        
        success(req, res, '获取角色绑定菜单成功', menus);
    } catch (err) {
        logger.error('获取角色绑定菜单错误', { error: err });
        serverError(req, res, '获取角色绑定菜单失败');
    }
};

// 获取角色已绑定的用户
const getBindUsers = async (req, res) => {
    
    const { id } = req.params;
    const { page, limit } = req.query;
    const filters = {};
    try {
        if (!validateId(Number(id))) {
            return badRequest(req, res, '角色ID格式错误');
        }
        
        // 获取当前用户ID
        const currentUserId = req.user?.id;

        const [users, total] = await Promise.all([
            RoleModel.getBindUsers(Number(id),page,limit, filters),
            RoleModel.getBindUsersCount(Number(id), filters)
        ]);

        success(req, res, '角色已绑定用户查询成功', {
            data:users,
            pagination: {
                page,
                limit,
                total,
                pages: Math.ceil(total / limit)
            }
        });
        
        // const users = await RoleModel.getBindUsers(id,currentUserId);
        // success(req, res, '获取角色绑定用户成功', users);
    } catch (err) {
        logger.error('获取角色绑定用户错误', { error: err });
        serverError(req, res, '获取角色绑定用户失败');
    }


};

// 获取角色已绑定的权限
const getBindPermissions = async (req, res) => {
    const { id } = req.params;
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        // 获取当前用户ID
        const currentUserId = req.user?.id;
        
        const permissions = await RoleModel.getBindPermissions(id,currentUserId);
        success(req, res, '获取角色绑定权限成功', permissions);
    } catch (err) {
        logger.error('获取角色绑定权限错误', { error: err });
        serverError(req, res, '获取角色绑定权限失败');
    }
};

// 获取角色可绑定的菜单
const getCanBindMenus = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        const menus = await RoleModel.getCanBindMenus(id);
        success(req, res, '获取角色可绑定菜单成功', menus);
    } catch (err) {
        logger.error('获取角色可绑定菜单错误', { error: err });
        serverError(req, res, '获取角色可绑定菜单失败');
    }
};

// 获取角色统计信息
const getRoleStats = async (req, res) => {
    try {
        const stats = await RoleModel.getRoleStats();
        success(req, res, '获取角色统计信息成功', stats);
    } catch (err) {
        logger.error('获取角色统计信息错误', { error: err });
        serverError(req, res, '获取角色统计信息失败');
    }
};

// 检查角色是否可以删除
const checkRoleDeletable = async (req, res) => {
    const { id } = req.params;
    
    try {
        if (!validateId(id)) {
            return badRequest(req, res, '角色ID格式错误');
        }

        const deletable = await RoleModel.isDeletable(id);
        
        success(req, res, '检查角色删除状态成功', {
            deletable,
            message: deletable ? '可以删除' : '不能删除，该角色为保护角色或已绑定用户/菜单'
        });
    } catch (err) {
        logger.error('检查角色删除状态错误', { error: err });
        serverError(req, res, '检查角色删除状态失败');
    }
};

// 判断当前用户的权限菜单是否变化更新（判断是否需要更新前端menu）
const checkRoleUpdate = async (req, res) => {
    try {
        
        // 先使用新的角色变化检测方法
        const hasRoleChanged = await RoleModel.hasRoleChanged(req.user.id);
        
        // 备用：如果角色没有变化，仍然调用原始方法检查菜单数量
        const menuCountCheck = await RoleModel.checkRoleUpdate(req.user.id);
        
        // 综合判断：角色变化或者菜单数量检查通过，则需要更新
        const needUpdate = hasRoleChanged || menuCountCheck;
        
        success(req, res, '检查角色菜单更新状态成功', { 
            needUpdate, 
            hasRoleChanged, // 额外返回角色是否变化的信息，便于调试
            menuCountCheck 
        });
    } catch (err) {
        logger.error('检查角色菜单更新状态错误', { error: err });
        serverError(req, res, '检查角色菜单更新状态失败');
    }
};



// 批量删除角色
const removeBatchRoles = async (req, res) => {
    const { ids } = req.body;
    
    try {
        // 输入验证
        const requiredValidation = validateRequired(req.body, ['ids']);
        if (!requiredValidation.isValid) {
            return badRequest(req, res, requiredValidation.message);
        }

        const idsValidation = validateArray(ids, '角色ID');
        if (!idsValidation.isValid) {
            return badRequest(req, res, idsValidation.message);
        }

        // 验证所有角色ID格式
        for (const id of ids) {
            if (!validateId(id)) {
                return badRequest(req, res, '角色ID格式错误');
            }
        }

        // 从认证中间件获取当前用户ID
        const currentUserId = req.user?.id;

        // 批量删除角色
        const affectedRows = await RoleModel.deleteBatch(ids, currentUserId);
        
        if (affectedRows > 0) {
            logger.info('批量删除角色成功', { roleIds: ids, affectedRows });
            // 清除相关用户的权限缓存
            // await PermissionModel.clearPermissionCache();
            
            // 清除角色列表缓存
            await cacheService.clearByPattern('app:role:list:*');
            logger.info('清除角色列表缓存');
            
            // 获取所有被删除角色绑定的用户ID并清除其缓存
            const userRolesSql = `
                SELECT DISTINCT user_id FROM user_role WHERE role_id IN (${ids.map(() => '?').join(',')})
            `;
            const [userRolesResult] = await db.execute(userRolesSql, ids);
            for (const row of userRolesResult) {
                await cacheService.clearByPattern(`app:user:roles:${row.user_id}`);
                await cacheService.del(generateCacheKey('user','permissions', row.user_id));
                await cacheService.del(generateCacheKey('user','permission_level', row.user_id));
                logger.info('清除用户相关缓存', { userId: row.user_id });
            }
            
            success(req, res, '批量删除角色成功', { affectedRows });
        } else {
            success(req, res, '没有可删除的角色', { affectedRows: 0 });
        }
    } catch (err) {
        logger.error('批量删除角色错误', { error: err, ids });
        if (err.message.includes('超级管理员') || err.message.includes('不可删除')) {
            badRequest(req, res, err.message);
        } else {
            serverError(req, res, '批量删除角色失败');
        }
    }
};

// 新增获取角色数据权限
const getRoleDataPermissions = async (req, res) => {
    try {
        const { roleId } = req.params;
        const { permissionType = 'read' } = req.query;
        
        // 验证角色ID格式
        if (!validateId(roleId)) {
            return badRequest(req, res, '角色ID格式错误');
        }
        
        // 检查角色是否存在
        const currentUserId = req.user?.id;
        const existingRole = await RoleModel.findById(roleId, currentUserId);
        if (!existingRole) {
            return notFound(req, res, '角色不存在');
        }
        
        // 生成缓存键，符合命名规范
        const cacheKey = generateCacheKey('data_permission', 'item', `role_${roleId}_type_${permissionType}`);
        
        // 尝试从缓存获取数据
        const cachedData = await cacheService.get(cacheKey);
        if (cachedData) {
            logger.info('从缓存获取角色数据权限', { roleId, permissionType });
            return success(req, res, '获取角色数据权限成功', cachedData);
        }
        
        const deptIds = await DataPermissionModel.getDataPermissionsByRoleId(roleId, permissionType);
        
        // 将结果存入缓存
        await cacheService.set(cacheKey, deptIds);
        logger.info('将角色数据权限存入缓存', { roleId, permissionType });
        
        return success(req, res, '获取角色数据权限成功', deptIds);
    } catch (err) {
        logger.error('获取角色数据权限失败:', { error: err });
        return serverError(req, res, '获取角色数据权限失败');
    }
};

// 新增分配角色数据权限
const assignRoleDataPermissions = async (req, res) => {
    try {
        const { roleId } = req.params;
        const { deptPermissions } = req.body;
        
        // 验证输入
        if (!validateId(roleId)) {
            return badRequest(req, res, '角色ID格式错误');
        }
        
        if (!Array.isArray(deptPermissions)) {
            return badRequest(req, res, '部门权限数据必须是数组');
        }
        
        // 检查角色是否存在
        const currentUserId = req.user?.id;
        const existingRole = await RoleModel.findById(roleId, currentUserId);
        if (!existingRole) {
            return notFound(req, res, '角色不存在');
        }
        
        // 检查当前用户的权限层级是否高于或等于要修改的角色
        if (!req.user?.isSuperAdmin) {
            // 使用Model方法替代直接db调用
            const userMaxLevel = await RoleModel.getUserMaxPermissionLevel(currentUserId);
            const role = await RoleModel.getRolePermissionLevel(roleId);
            
            if (!role || userMaxLevel < role.permission_level) {
                return error(req, res, '无权修改该角色的数据权限');
            }
        }
        
        await DataPermissionModel.assignDataPermissionsToRole(roleId, deptPermissions);
        
        // 清除相关缓存
        await cacheService.clearByPattern(`dataPermission:role:${roleId}:*`);
        logger.info('清除角色数据权限缓存', { roleId });
        
        return success(req, res, '数据权限分配成功');
    } catch (err) {
        logger.error('分配角色数据权限失败:', { error: err });
        return serverError(req, res, '分配角色数据权限失败');
    }
};

module.exports = {
    getAllRoles,
    getRoleById,
    createRole,
    updateRole,
    removeRole,
    removeBatchRoles,
    getBindRoles,
    getBindPermissions,
    batchBindUsers,
    bindMenus,
    getBindMenus,
    getBindUsers,
    getCanBindMenus,
    getRoleStats,
    checkRoleDeletable,
    checkRoleUpdate,
    getRoleDataPermissions,
    assignRoleDataPermissions
};